package dukeCE.InsightTracker;
/*
 * Topics page of the Insight Tracker- The first page after the log in page
 * 
 * 
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;


public class home_activity extends Activity{
    
    //private TabHost tabHost;     
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_activity);
        
   /*     Intent intentNewTopic = new Intent(this,post_activity.class);
        Intent intentCheckTopic = new Intent(this,home_activity.class);
        
        tabHost = getTabHost();     
        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Topics", null).setContent(intentCheckTopic));    
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("New Topics", null).setContent(intentNewTopic));    
        setContentView(tabHost);     
        */
        
        String exampleJsonInput="Nothing";
        //Connect to server and recive a JSON output
        //Normally we have to send out and $_POST['loginAuth'] to check if the user is valid, but we will get this done later
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://kevin2011.byethost3.com/adr_ch_2.php");
        try {
            // Add your data
        	/*
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("loginAuth", "This should be a hash code"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));*/
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            exampleJsonInput=getStringFromServerResponse(response.getEntity().getContent()).toString();        
        
        
        } catch (ClientProtocolException e) {
        	exampleJsonInput="Client error";
        } catch (IOException e) {
        	exampleJsonInput = "IO error";
        }

        
        //---------------------------------------------//
        
        //test the content of topics, these data should be pulling form db
        /*
        exampleJsonInput = "{\"topicCount\":2,\"topicList\":" + exampleJsonInput + "}";*/
        System.out.println(exampleJsonInput);
        
       exampleJsonInput = "{\"topicCount\":6,\"topicList\":[{\"" +
        		"topicId\":1,\"topicName\":\"Json \",\"topicDescription\":\"Gson is awsome\",\"isStarred\":true},{\"" +
        		"topicId\":2,\"topicName\":\"Topic 2\",\"topicDescription\":\"This is a second test\",\"isStarred\":false},{\"" +
        		"topicId\":3,\"topicName\":\"topic test name\",\"topicDescription\":\"This is a third test\",\"isStarred\":false},{\"" +
        		"topicId\":4,\"topicName\":\"Good topic\",\"topicDescription\":\"This is a description\",\"isStarred\":true},{\"" +
        		"topicId\":5,\"topicName\":\"Topic id\",\"topicDescription\":\"A topic id is unique\",\"isStarred\":true},{\"" +
        		"topicId\":6,\"topicName\":\"More data\",\"topicDescription\":\"This is just a test\",\"isStarred\":false}]}";
        
        Gson gson = new Gson();
        topicList listTopic= gson.fromJson(exampleJsonInput, topicList.class);
        int topicCount = listTopic.getCount();
        
        ArrayList<CheckableItem> items = new ArrayList<CheckableItem>();
        
        for(int i =0;i<topicCount;i++)
        	items.add(new CheckableItem(listTopic.getTopicByOrder(i).getName(),listTopic.getTopicByOrder(i).getDes(),listTopic.getTopicByOrder(i).isStarred()));
        
        
        CheckableItemAdapter itemAdapter = new CheckableItemAdapter(getApplicationContext(), R.layout.row, items);        
        ListView list = (ListView) findViewById(R.id.topicList);
        
        list.setAdapter(itemAdapter);
    }
    
    public void mainActivityClick(View view)
    {
    	int id = view.getId();
		switch (id) {
		case R.id.topicBt:
		startActivity(new Intent(this, MainMenuActivity.class));
		break;
		
		default:
			break;
		}
    }
    public void newTopic(View view) {
        Intent i = new Intent(getApplicationContext(), post_activity.class);
        startActivity(i);
    }
    
    public void search(View view) {
        Intent i = new Intent(getApplicationContext(), SearchActivity.class);
        startActivity(i);
    }
    
    
    
    // Read the output of httpresponse
    private StringBuilder getStringFromServerResponse(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        // Read response until the end
        try {
			while ((line = rd.readLine()) != null) { 
			    total.append(line); 
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        // Return full string
        return total;
    }
    //-------------------------------------------
    
    //This activates the camera activity and saves a picture as "test.jpg"
    private Uri outputFileUri;
    final int TAKE_PICTURE = 1;
    private void TakePhoto() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
 
		outputFileUri = Uri.fromFile(file);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, TAKE_PICTURE);
 
	}
    
    //activity result handler, currently catches completed camera activity and dispays image on main linear layout.
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case TAKE_PICTURE:
            if (resultCode == Activity.RESULT_OK) {
                Uri selectedImage = outputFileUri;
                getContentResolver().notifyChange(selectedImage, null);
                ImageView imageView = (ImageView) findViewById(R.id.linearLayout1);
                ContentResolver cr = getContentResolver();
                Bitmap bitmap;
                try {
                     bitmap = android.provider.MediaStore.Images.Media
                     .getBitmap(cr, selectedImage);

                    imageView.setImageBitmap(bitmap);
                    Toast.makeText(this, selectedImage.toString(),
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                            .show();
                    Log.e("Camera", e.toString());
                }
            }
        }
    }
    
}
